# -*- encoding: utf-8 -*-
'''
@File    :   cuckootest2.py
@Time    :   2021/09/10 16:57:13
@Author  :   Tan yunlin 
@Version :   2.0
@Contact :   3465126952@qq.com
@Desc    :   第二次进行实验测试
'''

# here put the import lib
from cuckoopy import CuckooFilter, bucket
import secrets
import timeit
import time
from cuckoopy.hashutils import fingerprint


def generate_message(bitSize):
    """
    产生一个bitSize大小的随机消息
    @bitSize:消息的位数
    """
    message = secrets.randbits(bitSize)
    mbit = f'{message:08b}'
    return mbit


def main(bucket_num, message_num):
    """
    测试不同桶的数量，不同消息数时使用布谷鸟过滤器的通信开销
    @bucket_num:桶的数量
    @message：消息的数量
    """
    fingerprint_size = 1  # 指纹占1byte
    bucket_size = 4  # 桶的大小：4
    capacity = bucket_num * bucket_size  #布谷鸟过滤器的容量
    ck = CuckooFilter(capacity, bucket_size,
                      fingerprint_size)  #每个位置四个座位，指纹字节长度为1

    # 产生指定数量8bit消息
    all_message = []
    for i in range(message_num):
        all_message.append(generate_message(8))

    # 将全部消息插入布谷鸟过滤器
    count = 1
    for message in all_message:
        if not ck.contains(message):
            ck.insert(message)
        else:
            # print(str(count) + ":" + message + "重复了！")
            count += 1

    # 测试采用布谷鸟过滤器时，不同数量的消息数对通信开销的影响
    unique_len = ck.size  #插入的消息数量
    secretsGenerator = secrets.SystemRandom()
    time0 = timeit.default_timer()
    # print("time0:", time0)
    for i in range(unique_len):
        time.sleep(secretsGenerator.uniform(0, 0.005))
    # print(timeit.default_timer() - time0)
    return timeit.default_timer() - time0


def NO_CuckooFilter(message_num):
    """
    测试不采用布谷鸟过滤器时，即所有消息（包括相同的消息）都会发送出去
    @message_num：消息的数量
    """
    secretsGenerator = secrets.SystemRandom()
    time1 = timeit.default_timer()
    for i in range(message_num):
        time.sleep(secretsGenerator.uniform(0, 0.005))
    # print(timeit.default_timer() - time1)
    return timeit.default_timer() - time1


if __name__ == "__main__":
    # 实验3目的：消息数量message_num从300取到1000，bucket_num=300、500、700，画三条曲线看效果
    # 使用布谷鸟过滤器
    # # bucket_num=300时
    # for message_num in range(300, 1100, 100):
    #     print(main(300, message_num))
    # print("=================================")
    # # bucket_num=500
    # for message_num in range(300, 1100, 100):
    #     print(main(500, message_num))
    # print("=================================")
    # # bucket_num=700
    # for message_num in range(300, 1100, 100):
    #     print(main(700, message_num))
    # 不使用布谷鸟过滤器
    for message_num in range(300, 1100, 100):
        print(NO_CuckooFilter(message_num))
    